package com.atguigu.day06;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.MapState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

public class Flink11_Timer_Exec_NoKeyedState {
    public static void main(String[] args) throws Exception {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        //2.从端口读数据并转为WaterSensor
        SingleOutputStreamOperator<WaterSensor> waterSensorSingleOutputStreamOperator = env.socketTextStream("localhost", 9999)

                .map(new MapFunction<String, WaterSensor>() {
                    @Override
                    public WaterSensor map(String value) throws Exception {
                        String[] split = value.split(",");
                        return new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
                    }
                });

        KeyedStream<WaterSensor, Tuple> keyedStream = waterSensorSingleOutputStreamOperator.keyBy("id");


        /**
         * 监控水位传感器的水位值，
         * 如果水位值在五秒钟之内连续上升，则报警，
         *
         *
         * 来一条数据注册（如果当前没有定时器的话）定时器定时时间为5S，并把定时时间保存在状态中，以便删除定时器的时候使用
         * 删除定时器时机，当发现在定时器报警前有水位没有上升则删除定时器，并重新在当前时间注册一个5S的定时器。
         *
         * 连续上升：要判断前后两个水位的差值，如果当前水位大于上一次水位则代表上升，如果没有大于则不符合连续上升，删除定时器，不让其报警
         *
         * 总结：要保存定时器的状态和水位的状态
         *
         * 并将报警信息输出到侧输出流。
         */

        SingleOutputStreamOperator<String> result = keyedStream.process(new KeyedProcessFunction<Tuple, WaterSensor, String>() {

            //保存上一次水位
            private Integer lastVc = Integer.MIN_VALUE;
            //保存定时器时间
            private Long timer = Long.MIN_VALUE;

            @Override
            public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {
                //1.判断水位是否上升
                if (value.getVc() > lastVc) {
                    //2.判断定时器是否已经注册
                    if (timer == Long.MIN_VALUE) {
                        //定时器没有注册
                        //注册定时器
                        timer = ctx.timerService().currentProcessingTime() + 5000;
                        System.out.println("注册定时器："+ctx.getCurrentKey()+":" + timer);
                        ctx.timerService().registerProcessingTimeTimer(timer);
                    }
                } else {
                    //水位没有上升
                    //删除定时器  如果有的话
                    if (timer != Long.MIN_VALUE) {
                        //证明有定时器，则删除
                        System.out.println("删除定时器"+ctx.getCurrentKey());
                        ctx.timerService().deleteProcessingTimeTimer(timer);
                        //将定时器时间恢复成初始值
                        timer = Long.MIN_VALUE;
                    }
                }

                //更新水位值，用来下一次水位做对比
                lastVc = value.getVc();
                out.collect(value.toString());

            }

            @Override
            public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
                //获取侧输出将报警信息发送至侧输出流中
                ctx.output(new OutputTag<String>("outPut") {
                }, "警报！！！！！水位5S连续上升");
                //将定时器时间恢复成初始值
                timer = Long.MIN_VALUE;
            }
        });

        result.print("主流");
        result.getSideOutput(new OutputTag<String>("outPut") {
        }).print("侧流");

        env.execute();

    }
}
